package com.example.springboot.controller;


import com.example.springboot.pojo.Result;
import com.example.springboot.pojo.User;
import com.example.springboot.pojo.Worker;
import com.example.springboot.service.UserService;
import com.example.springboot.service.WorkerService;
import com.example.springboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/userInfo")
public class UserInfo {

    @GetMapping("/")
    public Result<?> userInfo(@RequestHeader(name = "Authorization") String token) {
        Map<String, Object> map = JwtUtil.parseToken(token);
        return Result.success(map);
    }

    @Autowired
    UserService userService;
    @Autowired
    WorkerService workerService;

    @GetMapping("/newToken")
    public Result<?> newToken(String userType, String userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        if (userType.equals("业主")) {
            User u = userService.findByRoomNumber(userId);
            claims.put("name", u.getName());
            claims.put("phoneNumber", u.getPhoneNumber());
            claims.put("id", u.getId());
            claims.put("email", u.getEmail());
        } else if (userType.equals("工作人员")) {
            Worker w = workerService.findByWorkerId(userId);
            claims.put("name", w.getName());
            claims.put("phoneNumber", w.getPhoneNumber());
            claims.put("id", w.getId());
            claims.put("email", w.getEmail());
            claims.put("department", w.getDepartment());
        } else {
            return Result.error("不存在的用户类型");
        }
        String token = JwtUtil.genToken(claims);
        return Result.success(token);
    }
}
